<template>
    <div>
        <div>
            <PullRefresh v-model="loading" @refresh="onRefresh" :disabled="isRefresh">
                <MsgShow ref="msgShow" :chatData="chatData"  @arrive="topRefresh"  />
            </PullRefresh>
        </div>
        <div class="send-msg-box">
            <SendMsgBox @sendMsg="OnSendMsg" @sendVoice="OnSendVoice" />
        </div>


    </div>
</template>
<script setup>
import SendMsgBox from './SendMsgBox.vue';
import MsgShow from './MsgShow.vue';
import router from '@/router';
import { Local } from '@/utils/storage';
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { Button, PullRefresh, Sticky, Toast } from 'vant';
import {useGchatStore} from '@/stores/gchat';
import { connectSocket, disconnectSocket, sendMsgGroup, getHistory } from '@/utils/gsocket';
const gchatStore = useGchatStore();
const groupDetail = Local.get('chatInfo');
const userDetail = Local.get('userInfo');
const nickname=Local.get('nickname');
const msgShow = ref(null);
let socket = null;
const loading = ref(false);
const isRefresh=ref(true);
//通过计算属性获取当前聊天记录的位置
const chatData = computed(() => gchatStore.getInfo());
const tmpPos = computed(() => chatData.value.length);
const sendData = reactive({
    sendId: userDetail.userId,
    nickname:nickname,
    iconUrl:userDetail.iconUrl,
    groupId: groupDetail.id,
    messageType: 0,
    message: "",
    voice: null,
    duration: 0
});

 //监听对方是否发送消息给自己，交由页面监听，为的是能拉下去

const getInfo = reactive({
    groupId: groupDetail.id,
    pos: 0
});
onMounted(() => {
    //创建连接并获取历史聊天记录
    socket = connectSocket(userDetail.userId,groupDetail.id);
    getHistory(socket, getInfo);
    //初始化滑动
    setTimeout(() => {
        msgShow.value.scrollToBottom();
  }, 1000);
  socket.on("groupMessage", (data) => {
       const msgData = JSON.parse(data);
        gchatStore.addInfo(msgData);
        msgShow.value.scrollToBottom();
    });
});

onBeforeUnmount(() => {
    //断开连接
    gchatStore.removeInfo();
    disconnectSocket(socket);
});

const OnSendMsg = (message) => {
    sendData.message = message;
    sendData.messageType = 0;
    sendData.duration = 0;
    sendMsgGroup(socket, sendData);
    sendData.message = "";
}
const OnSendVoice = (voice,dur) => {
    sendData.voice = voice;
    sendData.messageType = 1;
    sendData.duration=dur;
    sendMsgGroup(socket, sendData);
    sendData.voice = null;
}
//防止下拉刷新和滑动冲突
const topRefresh = () => {
    isRefresh.value=false;
    setTimeout(() => {
    isRefresh.value = true;
  }, 1000);
}
const onRefresh = () => {
    isRefresh.value=true;
    setTimeout(() => {
        Toast('加载成功');
        getInfo.pos = tmpPos.value;
        getHistory(socket, getInfo);
        loading.value = false;
    }, 1000);
};
</script >
<style scoped>
.send-msg-box {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: auto;

}
</style>